import express from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import cookieSession from "cookie-session";
import multer from "multer";

const app = express();

//配置中间件
app.use(bodyParser.urlencoded({
    limit: "500mb",
    extended: false,
}));
app.use(bodyParser.json());
app.use(cookieParser("1000phone"));
app.use(cookieSession({
    name: "1000phone",
    keys: ["aaa", "bbb", "ccc"],
    maxAge: 1000 * 60 * 20
}))

const upload = multer({
    dest: "./../src/upload/"
});
app.use(upload.any());




app.use("*", (request, response, next) => {
    request.header("Content-Type", "application/json;charset=utf-8")
    // 判断是否路径在于白名单中 , 拦截器
    if (request.originalUrl.indexOf("/upload") != -1 ||
        request.originalUrl.indexOf("/js") != -1 ||
        request.originalUrl.indexOf("/index") != -1 ||
        request.originalUrl.indexOf("/css") != -1 ||
        request.originalUrl.indexOf("/images") != -1 ||
        request.originalUrl.indexOf("/goods") != -1 ||
        request.originalUrl.indexOf("/login") != -1 ||
        request.originalUrl.indexOf("/reg") != -1 ||
        request.originalUrl.indexOf("/header") != -1 ||
        request.originalUrl.indexOf("/footer") != -1) {
        next();
    } else {
        
        if (request.session["users"] == null || request.session["users"] == undefined) {
            response.json({
                msg: "请先登录!",
                status: -1
            })
            // 服务器端的重定向 response.redirect("./login.html"); 不能用ajax的请求
        } else {
            next();
        }
    }

})
//静态资源服务器
app.use(express.static("./../src"))

//挂载api路由对象
app.use("/api", require("./routes/ApiRoute").apiRouter)


app.listen(8081, () => {
    console.log("服务启动成功!,http://127.0.0.1:8081")
})